package cc.code.shapp.utils;

import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClickScreenUtil {

    static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public ClickScreenUtil() {
    }

    public static void clickScreenByXY(Integer x, Integer y) {
        try {
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Robot robot = new Robot();
            if (x == null) {
                x = toolkit.getScreenSize().width / 2;
            }
            if (y == null) {
                y = toolkit.getScreenSize().height / 2;
            }
            robot.mouseMove(x, y);
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        robot.setAutoDelay(3000);
        System.out.println("1.点击鼠标定位到作用域");
        clickScreenByXY(robot, 945,136);

        System.out.println("2.按两次空格键定位到文章列表");
        clickKeyBoard(robot, KeyEvent.VK_SPACE);
        clickKeyBoard(robot, KeyEvent.VK_SPACE);


        int x = getLocationX();
        int y = getLocationY();
        System.out.println("当前坐标为：" + "X-"+x + "Y-"+y);

        int count = 0;

        while(true) {
            System.out.println("目前点击文章次数： " + count);
            System.out.println(df.format(new Date()));
            System.out.println("点击文章");
            clickScreenByXY(robot, x, y);

            System.out.println("返回");
            clickScreenByXY(robot, 35, 52);

            y = y + 110;

            if(y > 1000) {
                clickScreenByXY(robot, 4, 500);

                clickKeyBoard(robot, KeyEvent.VK_SPACE);
                clickKeyBoard(robot, KeyEvent.VK_SPACE);

                y = 200;
                System.out.println("--当前坐标为：" + "X-"+getLocationX() + "Y-"+getLocationY());
            }
           count++;

        }
    }

    private static void clickScreenByXY(Robot robot, Integer x, Integer y) {
        robot.mouseMove(x, y);
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
    }

    private static void clickKeyBoard(Robot robot, int key) {
        robot.keyPress(key);
        robot.keyRelease(key);
    }

    private static int getLocationX() {
        Point point = java.awt.MouseInfo.getPointerInfo().getLocation();
        double x = point.getX();
        return (int)x;
    }

    private static int getLocationY() {
        Point point = java.awt.MouseInfo.getPointerInfo().getLocation();
        double y = point.getY();
        return (int)y;
    }


}
